package com.ybg.block.core.dbapi.service.impl;

import com.ybg.block.core.dbapi.dao.FnsChaincodeMapper;
import com.ybg.block.core.dbapi.entity.FnsApp;
import com.ybg.block.core.dbapi.dao.FnsAppMapper;
import com.ybg.block.core.dbapi.service.FnsAppService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ybg.block.core.fabricbak.utils.CacheUtil;
import com.ybg.block.core.fabricbak.utils.DateUtil;
import com.ybg.block.core.fabricbak.utils.MathUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yanyu
 * @since 2019-11-21
 */
@Service
public class FnsAppServiceImpl extends ServiceImpl<FnsAppMapper, FnsApp> implements FnsAppService {

    @Autowired
    private FnsChaincodeMapper chaincodeMapper;

    @Override
    public int add(FnsApp app) {
        if (null != baseMapper.check(app)) {
            return 0;
        }
        app.setAppKey(MathUtil.getRandom8());
        app.setCreateDate(DateUtil.getCurrent("yyyy-MM-dd HH:mm:ss"));
        app.setModifyDate(DateUtil.getCurrent("yyyy-MM-dd HH:mm:ss"));
        if (app.getActive()==1) {
            CacheUtil.putString(app.getAppKey(), chaincodeMapper.get(app.getChaincodeId()).getCc());
        }
        return baseMapper.add(app);
    }

    @Override
    public int update(FnsApp app) {
        FnsApp appTmp = baseMapper.get(app.getId());
        if (!StringUtils.equals(appTmp.getAppKey(), app.getAppKey())) {
            CacheUtil.removeString(appTmp.getAppKey());
            CacheUtil.removeAppBool(appTmp.getAppKey());
        }
        app.setModifyDate(DateUtil.getCurrent("yyyy-MM-dd HH:mm:ss"));
        CacheUtil.removeAppBool(app.getAppKey());
        return baseMapper.update(app);
    }

    @Override
    public int updateKey(int id) {
        FnsApp app = new FnsApp();
        app.setId(id);
        CacheUtil.removeString(baseMapper.get(id).getAppKey());
        app.setAppKey(MathUtil.getRandom8());
        if (app.getActive()==1) {
            CacheUtil.putString(app.getAppKey(), chaincodeMapper.get(app.getChaincodeId()).getCc());
        } else {
            CacheUtil.removeString(app.getAppKey());
        }
        return baseMapper.updateKey(app);
    }

    @Override
    public List<FnsApp> list(int id) {
        return baseMapper.list(id);
    }

    @Override
    public FnsApp get(int id) {
        return baseMapper.get(id);
    }

    @Override
    public int delete(int id) {
        return baseMapper.delete(id);
    }

    @Override
    public int deleteAll(int id) {
        return baseMapper.deleteAll(id);
    }

    @Override
    public int countById(int id) {
        return baseMapper.countById(id);
    }

    @Override
    public int count() {
        return baseMapper.count();
    }
}
